{% extends 'base/base.html' %}
{% load static %}
{% block title %}
    仪表盘-郑州移不动在线
{% endblock %}


{% block main %}
    <div class="container mt-3">
        {% if messages %}
            <div id="msg">
                {% for message in messages %}
                    <div class="alert alert-{% if message.tags == 'error' %}danger{% else %}{{ message.tags }}{% endif %} alert-dismissible fade in"
                         role="alert">
                        {{ message }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                    </div>
                {% endfor %}
            </div>
            <script>
                // 1.5 秒后淡出，可改成任意延时
                setTimeout(() => {
                    document.getElementById('msg').style.transition = 'opacity 0.5s';
                    document.getElementById('msg').style.opacity = '0';
                    // 如果想彻底移除再加一句 remove()
                }, 1500);
            </script>
        {% endif %}
    </div>
    <div id="myCarousel" class="carousel slide" data-ride="carousel">
        <!-- 指示点 -->
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
        </ol>

        <!-- 幻灯片 -->
        <div class="carousel-inner" role="listbox">
            <div class="item active">
                <img style="height: 680px;width: 1140px" src="{% static 'phone/zhuanye.jpeg' %}" alt="First slide">
            </div>
            <div class="item">
                <img style="height: 680px;width: 1140px" src="{% static 'phone/dianxin.jpg' %}" alt="Second slide">
            </div>
            <div class="item">
                <img style="height: 680px;width: 1140px" src="{% static 'phone/yidong.webp' %}" alt="Third slide">
            </div>
        </div>

        <!-- 左右箭头 -->
        <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        </a>
        <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        </a>
    </div>
    {% if primary_phone %}
        <h1>仪表盘</h1>
        <ul class="list-group">
            <li class="list-group-item">手机号码:{{ primary_phone }}</li>
            {% if phone_combo.combo.id %}
                <li class="list-group-item">套餐信息:{{ phone_combo.combo.name }}
                    <a style="float: right; margin-top: -7px" class="btn btn-warning"
                       href="{% url 'main:combo_detail' phone_combo.combo.id %}" role="button">详情</a>
                    {% else %}
                <li class="list-group-item">套餐信息: 没有套餐信息 请先添加套餐
                <a style="float: right; margin-top: -7px" class="btn btn-warning" href="{% url 'main:index' %}"
                   role="button">详情</a>
            {% endif %}
            </li>
            <li class="list-group-item">余额:{{ balance.amount }}
                <a style="float: right; margin-top: -7px" class="btn btn-success"
                   href="{% url 'main:add_money' primary_phone.id %}" role="button">充值</a></li>
            <li class="list-group-item">剩余流量:{{ balance.data_remaining }}
                <a style="float: right; margin-top: -7px" class="btn btn-success" href="#"
                   role="button">模拟使用10MB</a></li>
            <li class="list-group-item">剩余语音:{{ balance.voice_remaining }}
                <a style="float: right; margin-top: -7px" class="btn btn-success" href="#"
                   role="button">模拟使用10分钟</a></li>
            <li class="list-group-item">剩余短信:{{ balance.sms_remaining }}
                <a style="float: right; margin-top: -7px" class="btn btn-success" href="#"
                   role="button">模拟使用10条</a></li>
        </ul>
        <h4>快速入口</h4>
        <div class="quick-actions" role="group" aria-label="快捷功能">
            <a class="quick-btn success" href="{% url 'main:add_money' primary_phone.id %}" role="button">
                <span class="icon"></span> 金额充值
            </a>
            <a class="quick-btn warning" href="{% url 'main:combo_choice' primary_phone.id %}" role="button">
                <span class="icon"></span> 套餐管理
            </a>
            <button class="quick-btn info record_btn" type="button">
                <span class="icon"></span> 使用记录
            </button>
            <button class="quick-btn purple payment_btn" type="button">
                <span class="icon"></span> 缴费记录
            </button>
        </div>
    {% else %}
        <h1>当前用户没有号码，请先添加号码</h1>
    {% endif %}

    <div class="payment" id="payment-panel" style="display: none">
        {% if recent_payments %}
            <ul class="list-group">
                <li class="list-group-item disabled">{{ primary_phone.phonenumber }} 缴费记录</li>
                {% for payment in recent_payments %}
                    {% if payment.pay_method == 'alipay' %}
                        <li class="list-group-item">{{ payment.payment_time }}
                            通过 支付宝 缴费{{ payment.amount }}元
                        </li>
                    {% elif payment.pay_method == 'wechat' %}
                        <li class="list-group-item">{{ payment.payment_time }}
                            通过 微信 缴费{{ payment.amount }}元
                        </li>
                    {% elif payment.pay_method == 'bank' %}
                        <li class="list-group-item">{{ payment.payment_time }}
                            通过 银行卡 缴费{{ payment.amount }}元
                        </li>
                    {% elif payment.pay_method == 'cash' %}
                        <li class="list-group-item">{{ payment.payment_time }}
                            通过 现金 缴费{{ payment.amount }}元
                        </li>

                    {% endif %}
                {% endfor %}
            </ul>
            <nav aria-label="Payment pagination" class="text-center">
                <ul class="pagination">
                    {% if recent_payments.has_previous %}
                        <li><a href="?payment_page={{ recent_payments.previous_page_number }}&record_page={{ recent_use_recode.number }}#payment-panel">&laquo;</a></li>
                    {% else %}
                        <li class="disabled"><span>&laquo;</span></li>
                    {% endif %}

                    {% for num in recent_payments.paginator.page_range %}
                        {% if num == recent_payments.number %}
                            <li class="active"><span>{{ num }}</span></li>
                        {% else %}
                            <li><a href="?payment_page={{ num }}&record_page={{ recent_use_recode.number }}#payment-panel">{{ num }}</a></li>
                        {% endif %}
                    {% endfor %}

                    {% if recent_payments.has_next %}
                        <li><a href="?payment_page={{ recent_payments.next_page_number }}&record_page={{ recent_use_recode.number }}#payment-panel">&raquo;</a></li>
                    {% else %}
                        <li class="disabled"><span>&raquo;</span></li>
                    {% endif %}
                </ul>
            </nav>
        {% endif %}
    </div>
    <div class="record" id="record-panel" style="display: none">
        {% if recent_use_recode %}
            <ul class="list-group">
                <li class="list-group-item disabled">{{ primary_phone.phonenumber }} 使用记录</li>
                {% for use_record in recent_use_recode %}
                    {% if use_record.usage_type == 'data' %}
                        <li class="list-group-item">{{ use_record.usage_time }}
                            使用 流量 {{ use_record.amount_used }} MB
                        </li>
                    {% elif use_record.usage_type == 'voice' %}
                        <li class="list-group-item">{{ use_record.usage_time }}
                            使用 通话 {{ use_record.amount_used }} 分钟
                        </li>
                    {% elif use_record.usage_type == 'sms' %}
                        <li class="list-group-item"> {{ use_record.usage_time }}
                            发送 短信 {{ use_record.amount_used }} 条
                        </li>

                    {% endif %}
                {% endfor %}
            </ul>
            <nav aria-label="Usage pagination" class="text-center">
                <ul class="pagination">
                    {% if recent_use_recode.has_previous %}
                        <li><a href="?record_page={{ recent_use_recode.previous_page_number }}&payment_page={{ recent_payments.number }}#record-panel">&laquo;</a></li>
                    {% else %}
                        <li class="disabled"><span>&laquo;</span></li>
                    {% endif %}

                    {% for num in recent_use_recode.paginator.page_range %}
                        {% if num == recent_use_recode.number %}
                            <li class="active"><span>{{ num }}</span></li>
                        {% else %}
                            <li><a href="?record_page={{ num }}&payment_page={{ recent_payments.number }}#record-panel">{{ num }}</a></li>
                        {% endif %}
                    {% endfor %}

                    {% if recent_use_recode.has_next %}
                        <li><a href="?record_page={{ recent_use_recode.next_page_number }}&payment_page={{ recent_payments.number }}#record-panel">&raquo;</a></li>
                    {% else %}
                        <li class="disabled"><span>&raquo;</span></li>
                    {% endif %}
                </ul>
            </nav>
        {% endif %}
    </div>
{% endblock %}

{% block js %}
    <script>
        $('.record_btn').on('click', function () {
            $('.payment').attr('style', 'display: none')
            $('.record').attr('style', 'margin-top: 20px;display: block')

        })
    </script>
    <script>
        $('.payment_btn').on('click', function () {
            $('.payment').attr('style', 'margin-top: 20px;display:block')
            $('.record').attr('style', 'display: none')

        })
    </script>
    <script>
        // 根据 URL 哈希或查询参数自动展开对应面板（优先使用哈希）
        (function(){
            var hash = window.location.hash;
            if (hash === '#payment-panel') {
                $('.payment').attr('style', 'margin-top: 20px;display:block');
                $('.record').attr('style', 'display: none');
                return;
            }
            if (hash === '#record-panel') {
                $('.payment').attr('style', 'display: none');
                $('.record').attr('style', 'margin-top: 20px;display: block');
                return;
            }

            var params = new URLSearchParams(window.location.search);
            var pay = params.get('payment_page');
            var rec = params.get('record_page');
            if (pay && !rec) {
                $('.payment').attr('style', 'margin-top: 20px;display:block');
                $('.record').attr('style', 'display: none');
                return;
            }
            if (rec && !pay) {
                $('.payment').attr('style', 'display: none');
                $('.record').attr('style', 'margin-top: 20px;display: block');
                return;
            }
            // 若同时存在或都不存在，保持初始状态（都隐藏）
        })();
    </script>
    <script>
        // 在页面注入一个隐藏的 CSRF input，确保能读取到 token
        // 即使没有表单，这里也会让后端发放 CSRF cookie
        document.body.insertAdjacentHTML('beforeend', '<div id="csrf-holder" style="display:none">{% csrf_token %}</div>');

        // 通过“充值”按钮的 href 提取当前号码 ID
        function getPhoneId() {
            var href = $('a.btn.btn-success[href*="add_money"]').attr('href') || '';
            var m = href.match(/add_money\/(\d+)/);
            return m ? parseInt(m[1], 10) : null;
        }

        // 获取 CSRF Token（来自 cookie）
        function getCsrfToken() {
            var m = document.cookie.match(/csrftoken=([^;]+)/);
            if (m) return m[1];
            var el = document.querySelector('#csrf-holder input[name="csrfmiddlewaretoken"]');
            return el ? el.value : '';
        }

        // 计算正确的应用前缀（可能是 '/main/' 或 '/'）
        function getAppPrefix() {
            var href = $('a.btn.btn-success[href*="add_money"]').attr('href') || '';
            var idx = href.indexOf('add_money');
            return idx > -1 ? href.slice(0, idx) : '/';
        }

        function simulateUse(action, amount) {
            var phoneId = getPhoneId();
            if (!phoneId) { alert('未获取到号码ID'); return Promise.reject(); }
            var base = getAppPrefix();
            return fetch(base + 'simulate/' + action + '/' + phoneId + '/' + amount + '/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin'
            }).then(function(resp){ return resp.json(); });
        }

        // 不更改现有按钮 HTML，基于文本选择器绑定事件
        $('a.btn.btn-success:contains("模拟使用10MB")').on('click', function (e) {
            e.preventDefault();
            var btn = this; btn.disabled = true;
            simulateUse('data', 10).then(function (json) {
                if (json && json.ok) { location.reload(); }
                else { alert((json && json.message) || '操作失败'); }
            }).catch(function(){ alert('网络异常'); }).finally(function(){ btn.disabled = false; });
        });

        $('a.btn.btn-success:contains("模拟使用10分钟")').on('click', function (e) {
            e.preventDefault();
            var btn = this; btn.disabled = true;
            simulateUse('voice', 10).then(function (json) {
                if (json && json.ok) { location.reload(); }
                else { alert((json && json.message) || '操作失败'); }
            }).catch(function(){ alert('网络异常'); }).finally(function(){ btn.disabled = false; });
        });

        $('a.btn.btn-success:contains("模拟使用10条")').on('click', function (e) {
            e.preventDefault();
            var btn = this; btn.disabled = true;
            simulateUse('sms', 10).then(function (json) {
                if (json && json.ok) { location.reload(); }
                else { alert((json && json.message) || '操作失败'); }
            }).catch(function(){ alert('网络异常'); }).finally(function(){ btn.disabled = false; });
        });
    </script>
{% endblock %}

